package com.esl.coordinator.client.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VerySimpleClient {
	static final Logger LOG = LoggerFactory.getLogger(VerySimpleClient.class);

	private String serverHostname = null;
	private int serverPort = 0;
	private byte[] data = null;
	private Socket sock = null;
	private InputStream sockInput = null;
	private OutputStream sockOutput = null;

	public VerySimpleClient(String serverHostname, int serverPort, byte[] data) {
		this.serverHostname = serverHostname;
		this.serverPort = serverPort;
		this.data = data;
	}

	public void sendSomeMessages(int iterations) {
		LOG.info("Opening connection to " + serverHostname + " port "
				+ serverPort);
		try {
			sock = new Socket(serverHostname, serverPort);
			sockInput = sock.getInputStream();
			sockOutput = sock.getOutputStream();
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}

		LOG.info("About to start reading/writing to/from socket.");

		byte[] buf = new byte[data.length];
		int bytes_read = 0;
		for (int loopi = 1; loopi <= iterations; loopi++) {
			try {
				sockOutput.write(data, 0, data.length);
				bytes_read = sockInput.read(buf, 0, buf.length);
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
			}
			if (bytes_read < data.length) {
				LOG.info("run: Sent " + data.length
						+ " bytes, server should have sent them back, read "
						+ bytes_read + " bytes, not the same number of bytes.");
			} else {
				LOG.info("Sent "
						+ bytes_read
						+ " bytes to server and received them back again, msg = "
						+ (new String(data)));
			}

			// Sleep for a bit so the action doesn't happen to fast - this is
			// purely for reasons of demonstration, and not required
			// technically.
			try {
				Thread.sleep(50);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		}

		LOG.info("Done reading/writing to/from socket, closing socket.");

		try {
			sock.close();
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}
	}

	public static void main(String argv[]) {
		String hostname = "localhost";
		int port = 9999;
		byte[] data = "Hello World".getBytes();

		VerySimpleClient client = new VerySimpleClient(hostname, port, data);
		client.sendSomeMessages(1);
	}
}
